<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text>←</text>
      </view>
      <text class="header-title">购物车</text>
      <view class="header-actions">
        <text class="clear-btn" @click="clearCart" v-if="cartItems.length > 0">清空</text>
      </view>
    </view>

    <!-- 购物车内容 -->
    <view class="cart-content">
      <!-- 空状态 -->
      <view v-if="cartItems.length === 0" class="empty-cart">
        <text class="empty-icon">🛒</text>
        <text class="empty-text">购物车是空的</text>
        <text class="empty-desc">去添加一些美食吧</text>
        <text class="browse-btn" @click="navigateToMenu">浏览菜单</text>
      </view>

      <!-- 购物车列表 -->
      <view v-else class="cart-items">
        <view 
          v-for="(item, index) in cartItems" 
          :key="item.id"
          class="cart-item"
        >
          <image :src="item.image || '/static/food/default.jpg'" class="item-image" />
          <view class="item-details">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-price">${{ item.price }}</text>
            <view class="quantity-controls">
              <text class="quantity-btn" @click="decreaseQuantity(index)">-</text>
              <text class="quantity">{{ item.quantity }}</text>
              <text class="quantity-btn" @click="increaseQuantity(index)">+</text>
            </view>
          </view>
          <view class="item-total">
            <text class="total-price">${{ (item.price * item.quantity).toFixed(2) }}</text>
            <text class="remove-btn" @click="removeItem(index)">×</text>
          </view>
        </view>
      </view>

      <!-- 订单摘要 -->
      <view v-if="cartItems.length > 0" class="order-summary">
        <view class="summary-item">
          <text>小计</text>
          <text>${{ subtotal.toFixed(2) }}</text>
        </view>
        <view class="summary-item">
          <text>税费 (8.875%)</text>
          <text>${{ tax.toFixed(2) }}</text>
        </view>
        <view class="summary-item total">
          <text>总计</text>
          <text>${{ total.toFixed(2) }}</text>
        </view>
      </view>

      <!-- 桌号输入 -->
      <view v-if="cartItems.length > 0" class="table-input">
        <text class="input-label">桌号</text>
        <input
          class="input-field"
          type="number"
          placeholder="请输入桌号"
          v-model="tableNumber"
        />
      </view>

      <!-- 顾客信息 -->
      <view v-if="cartItems.length > 0" class="customer-info">
        <text class="section-title">顾客信息</text>
        <view class="input-group">
          <input
            class="input-field"
            placeholder="姓名 (可选)"
            v-model="customerName"
          />
        </view>
        <view class="input-group">
          <input
            class="input-field"
            placeholder="电话 (可选)"
            type="tel"
            v-model="customerPhone"
          />
        </view>
      </view>

      <!-- 结算按钮 -->
      <view v-if="cartItems.length > 0" class="checkout-section">
        <text class="checkout-btn" @click="checkout">立即结算</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text>处理中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  data() {
    return {
      tableNumber: '',
      customerName: '',
      customerPhone: '',
      loading: false
    }
  },

  computed: {
    ...mapState(['cartItems']),
    
    subtotal() {
      return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
    },

    tax() {
      return this.subtotal * 0.08875
    },

    total() {
      return this.subtotal + this.tax
    }
  },

  methods: {
    ...mapMutations([
      'updateCartItem',
      'removeCartItem',
      'clearCart'
    ]),

    increaseQuantity(index) {
      const item = this.cartItems[index]
      this.updateCartItem({
        index,
        item: { ...item, quantity: item.quantity + 1 }
      })
    },

    decreaseQuantity(index) {
      const item = this.cartItems[index]
      if (item.quantity > 1) {
        this.updateCartItem({
          index,
          item: { ...item, quantity: item.quantity - 1 }
        })
      } else {
        this.removeItem(index)
      }
    },

    removeItem(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个菜品吗？',
        success: (res) => {
          if (res.confirm) {
            this.removeCartItem(index)
            uni.showToast({
              title: '已删除',
              icon: 'success'
            })
          }
        }
      })
    },

    async checkout() {
      // 验证输入
      if (!this.tableNumber) {
        uni.showToast({
          title: '请输入桌号',
          icon: 'none'
        })
        return
      }

      if (this.tableNumber < 1 || this.tableNumber > 100) {
        uni.showToast({
          title: '请输入有效的桌号(1-100)',
          icon: 'none'
        })
        return
      }

      this.loading = true

      try {
        const orderData = {
          table_number: parseInt(this.tableNumber),
          customer_name: this.customerName,
          customer_phone: this.customerPhone,
          items: this.cartItems.map(item => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            image: item.image
          })),
          total_amount: this.subtotal,
          tax_amount: this.tax,
          grand_total: this.total
        }

        const res = await uni.request({
          url: 'http://localhost/api/orders',
          method: 'POST',
          data: orderData,
          header: {
            'Content-Type': 'application/json'
          }
        })

        if (res.data.success) {
          // 清空购物车
          this.clearCart()
          
          // 跳转到订单详情页
          uni.redirectTo({
            url: `/pages/orders/detail?id=${res.data.data.id}`
          })
          
          uni.showToast({
            title: '订单创建成功',
            icon: 'success'
          })
        } else {
          throw new Error(res.data.message)
        }

      } catch (error) {
        console.error('下单失败:', error)
        uni.showToast({
          title: '下单失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    goBack() {
      uni.navigateBack()
    },

    navigateToMenu() {
      uni.switchTab({
        url: '/pages/menu/menu'
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 0;
  background: #f8f8f8;
  min-height: 100vh;
}

.header {
  background: white;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  font-size: 36rpx;
  padding: 10rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.clear-btn {
  color: #ff6b6b;
  font-size: 28rpx;
}

.cart-content {
  padding: 20rpx;
}

.empty-cart {
  text-align: center;
  padding: 100rpx 0;
  background: white;
  border-radius: 20rpx;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 36rpx;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 40rpx;
}

.browse-btn {
  background: #ff6b6b;
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 30rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.cart-items {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.cart-item {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  align-items: center;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 15rpx;
  background: #f0f0f0;
  margin-right: 30rpx;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.item-price {
  font-size: 28rpx;
  color: #ff6b6b;
  display: block;
  margin-bottom: 15rpx;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.quantity-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  font-weight: bold;
}

.quantity {
  font-size: 32rpx;
  font-weight: bold;
  min-width: 60rpx;
  text-align: center;
}

.item-total {
  text-align: right;
  margin-left: 20rpx;
}

.total-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
  display: block;
  margin-bottom: 10rpx;
}

.remove-btn {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

.order-summary {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.summary-item.total {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
  margin-top: 20rpx;
}

.table-input,
.customer-info {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.input-label {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.input-group {
  margin-bottom: 20rpx;
}

.input-group:last-child {
  margin-bottom: 0;
}

.input-field {
  border: 2rpx solid #e0e0e0;
  border-radius: 15rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #f8f8f8;
  width: 100%;
}

.input-field:focus {
  border-color: #ff6b6b;
  outline: none;
}

.checkout-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
}

.checkout-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  text-align: center;
  padding: 25rpx;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
  display: block;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  background: white;
  padding: 60rpx;
  border-radius: 20rpx;
  text-align: center;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #ff6b6b;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>